﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using blackhouse.BlackApart.Business.Apartments;
using blackhouse.BlackApart.Business;

namespace blackhouse.BlackApart.Web {
	public class DisplayApartmentTypeState {

		#region Fields

		private const string ITEMS_KEY = "DisplayApartmentTypeState";

		#endregion

		#region Properties

		public DisplayApartmentTypeView View { get; set; }
		public IApartmentGroup ApartmentType { get; set; }
		public int Page { get; set; }
		public IApartment DefaultApartment { get; set; }

		#endregion

		#region Constructors

		private DisplayApartmentTypeState() { }

		#endregion

		#region Methods

		public static void RedirectIfIncorectUrl() {
			if (HttpContext.Current.Request["forceurl"] == "1") return;
			if (HttpContext.Current == null || HttpContext.Current.Items == null || HttpContext.Current.Request == null) return;
			DisplayApartmentTypeState state = GetCurrentState();
			SearchState queryState = SearchState.GetFromContext();
			if (state == null) return;
			string rightUrl = UrlUtils.GetApartmentTypeUrl(Factory.Instance().GetPreFolderEvaluation(), state.ApartmentType, state.View, state.Page);
			if (!HttpContext.Current.Request.RawUrl.EndsWith(rightUrl))
				HttpContext.Current.Response.RedirectPermanent(rightUrl, true);
		}

		public static DisplayApartmentTypeState GetCurrentState() {
			if (HttpContext.Current == null || HttpContext.Current.Items == null || HttpContext.Current.Request == null) return null;

			DisplayApartmentTypeState state = null;
			if (HttpContext.Current.Items.Contains(ITEMS_KEY))
				state = HttpContext.Current.Items[ITEMS_KEY] as DisplayApartmentTypeState;

			if (state == null) {
				int apartmentTypeId = 0;
				if (!Int32.TryParse(HttpContext.Current.Request[UrlUtils.ParameterApartmentTypeId], out apartmentTypeId)) return null;
				DisplayApartmentTypeView view = default(DisplayApartmentTypeView);
				Enum.TryParse<DisplayApartmentTypeView>(HttpContext.Current.Request[UrlUtils.ParameterApartmentTypeView], true, out view);
				if (!Enum.IsDefined(typeof(DisplayApartmentTypeView), view)) view = DisplayApartmentTypeView.Default;
				int page = 0;
				if (!Int32.TryParse(HttpContext.Current.Request[UrlUtils.ParameterPage], out page)) page = 1;
				if (page <= 0) page = 1;
				state = new DisplayApartmentTypeState();
				state.ApartmentType = Factory.Instance().GetApartmentGroup(apartmentTypeId);
				state.DefaultApartment = state.ApartmentType.GetApartments().First();
				state.Page = page;
				state.View = view;
				HttpContext.Current.Items.Add(ITEMS_KEY, state);
			}
			return state;
		}

		#endregion

	}
}